<?php

// +---------------------------------------------+
// |     Copyright  2010 - 2018 InterPhoto       |
// |     http://www.weentech.com                 |
// |     This file may not be redistributed.     |
// +---------------------------------------------+

if(!defined('INTERPHOTO')) die('File not found!');


// ########################## LOAD ADMIN SESSION #############################

if(is_dir(BASEPATH . 'install/'))
{
	$needDeleteInstall = 1;
	LogIn();
}else{
	$needDeleteInstall = 0;
}

$userid = '';
$logininfo = '';

define('USERIP', GetIP());
define('COOKIE_NAME', 'InterPhotoM'.COOKIE_KEY);
define('ONE_WEEK', 60*60*24*7);
define('TIMENOW', time());


if(ForceInt($mainsettings['adminCookieTimeout']) <= 0)
{
	$mainsettings['adminCookieTimeout'] = 1800;
}


$loginusername = ForceIncomingString('loginusername');
$loginpassword = ForceIncomingString('loginpassword');

// check and secure login info
if(strlen($loginusername) AND strlen($loginpassword))
{
	// first secure the data
 
	if(!isName($loginusername) OR !isPass($loginpassword)){
		$logininfo = '用户名或密码存在非法字符!';
		LogIn();
	}

	$userid = LoginUser($loginusername, $loginpassword);
	
	if(empty($userid) OR $userid <= 0 )
	{
		$logininfo = '用户不存在或密码错误!';
		LogIn();
	}else	{
		CreateSession($userid);
		header("Location: index.php");
		exit();
	}

} else if (ForceIncomingInt('logout') == 1) {

	$sessionid = ForceString(ForceIncomingCookie(COOKIE_NAME));

	if(!empty($sessionid))
	{
		   $DB->query("DELETE FROM " . TABLE_PREFIX . "sessions WHERE sessionid = '$sessionid'");
	}

	$DB->query("DELETE FROM " . TABLE_PREFIX . "vvc WHERE date < " . (TIMENOW - 3600*6));
	$DB->query("DELETE FROM " . TABLE_PREFIX . "sessions WHERE lastactivity < " . (TIMENOW - 3600*48));
	setcookie(COOKIE_NAME, "", TIMENOW + ONE_WEEK, "/");
	LogIn();

} else if (!defined('IN_GETPASS')) {

	$sessionid = ForceIncomingCookie(COOKIE_NAME);

	if($sessionid AND IsPass($sessionid))
	{
		$sql = "SELECT u.userid, u.username, u.activated, ug.* FROM " . TABLE_PREFIX . "sessions s
					LEFT JOIN " . TABLE_PREFIX . "users u ON u.userid = s.userid
					LEFT JOIN " . TABLE_PREFIX . "usergroups ug ON ug.groupid = u.groupid AND ug.manage = 1
					WHERE s.sessionid    = '$sessionid'
					AND   s.ipaddress = '" . USERIP . "'
					AND   s.lastactivity > " . (TIMENOW - $mainsettings['adminCookieTimeout']) . "
					AND   s.location = 1
					AND   s.admin = 1
					AND   u.activated = 1
					AND   ug.manage = 1";

		$userinfo = $DB->query_first($sql);
		if(!$userinfo OR !$userinfo['userid']){
			AdminLoginOut();
		}else{
			$DB->query("UPDATE " . TABLE_PREFIX . "sessions SET lastactivity = " . TIMENOW . "  WHERE sessionid    = '$sessionid' ");
		}

	}else{
		AdminLoginOut();
	}

}


define('TEMPLATEPATH', 'templates/');
unset($userid, $loginusername, $loginpassword, $sessionid);

// ####################################################################

function LogIn()
{
	global $needDeleteInstall, $logininfo, $DB;

	$DB->close();

	if($needDeleteInstall)
	{
		$logininfo ='提示: 请在删除系统安装目录(./install/)后继续!';
		$disabled =  ' disabled="disabled" style="cursor:default;"';
	}else{
		$inputfocus = 'onLoad="document.forms.wcloginform.loginusername.focus()"';
	}
	

	echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
	<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>InterPhoto图片网站管理系统 - 管理登录</title>
	<link rel=stylesheet href=\'./templates/login.css\' />
	<SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT">
		<!--
			if(top.location != self.location)
		{
			top.location.replace(self.location)
		}
		-->
	</SCRIPT>
	</head>
	<body id="page-login" '. $inputfocus .' >
	<div class="login-container">
	<div class="login-box">
		<form action="index.php" method="post" name="wcloginform">
			<fieldset class="login-form">
				<h2>InterPhoto图片网站管理系统 - 管理登录</h2>
				<div id="messages">' . $logininfo . '</div>
				<div class="input-box input-left"><label for="username">用户名:</label><br/>
					<input type="text" id="username" name="loginusername" value="" class="required-entry input-text" '.$disabled .'/></div>
				<div class="input-box input-right"><label for="login">密码:</label><br/>
					<input type="password" id="login" name="loginpassword" class="required-entry input-text" value="" '.$disabled .'/></div>
				<div class="clear"></div>
				<div class="form-buttons" style="margin-right:8px;"><input type="submit" class="form-button" value="登 录" '.$disabled .'/></div>
				<div style="margin-left:8px;"><a href="admin.getpass.php" target="_parent" class="normal">找回密码?</a>&nbsp;</div>
			</fieldset>
			<p class="legal" align="right"><a href="http://www.weentech.com" target="_blank" class="normal">闻泰网络</a> <font color=#FF9900>&copy;</font><font class="copyright">'.date("Y").'</font>&nbsp;</p>
		</form>
		<div class="bottom"></div>
	</div>
	</div>
	</body>
	</html>';

	exit();
}

function LoginUser($loginusername, $loginpassword)
{
	global $DB;

	$loginpassword = md5($loginpassword);

	$user = $DB->query_first("SELECT u.userid FROM " . TABLE_PREFIX . "users u LEFT JOIN  " . TABLE_PREFIX . "usergroups ug ON (u.groupid = ug.groupid) WHERE u.username = '$loginusername' AND u.password = '$loginpassword' AND u.activated = 1 AND ug.manage = 1");

	return Iif(isset($user), $user['userid'], 0);
}


function AdminLoginOut(){
	  if(defined('ADMIN_LOGIN'))
	  {
			LogIn();
	  } else {
			setcookie(COOKIE_NAME, "", TIMENOW + ONE_WEEK, "/");
			header("Location: index.php");
			exit;
	  }
}


function CreateSession($userid)
{
	global $DB;

	$useragent = substr(addslashes($_SERVER['HTTP_USER_AGENT']), 0, 252);

	$session = array('sessionid'    => md5(uniqid($userid . COOKIE_KEY)),
				   'userid'       => $userid,
				   'ipaddress'    => USERIP,
				   'useragent'    => $useragent,
				   'lastactivity' => TIMENOW);

	$DB->query("REPLACE INTO " . TABLE_PREFIX . "sessions (sessionid, userid, ipaddress, useragent, lastactivity, location, loggedin, admin)
			  VALUES ('" . $session['sessionid'] . "', '" . $session['userid'] . "', '" . $session['ipaddress'] . "', '" . $session['useragent'] . "', '" . $session['lastactivity'] . "', 1,  1, 1) ");
	$DB->query("UPDATE " . TABLE_PREFIX . "users SET lastactivity = " . TIMENOW . "  WHERE userid    = '$userid' ");

	setcookie(COOKIE_NAME, $session['sessionid'], TIMENOW + ONE_WEEK, "/");
}


?>